<template>
  <div class="add-customer">
    <h2>新增客户</h2>
    <div class="form-container">
      <div class="section">
        <h3>基础信息</h3>
        <el-form :model="form" label-width="100px" :rules="rules" ref="form">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="客户编号" prop="customerNo">
                <el-input 
                  v-model="form.customerNo" 
                  :placeholder="form.isSystemNo ? '系统自动生成' : '请输入客户编号'" 
                  :disabled="form.isSystemNo"
                >
                  <el-checkbox 
                    slot="append" 
                    v-model="form.isSystemNo" 
                    @change="handleSystemNoChange"
                  >
                    系统编号
                  </el-checkbox>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户名称" prop="customerName">
                <el-input v-model="form.customerName" placeholder="请输入客户名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="营业性质" prop="businessNature">
                <el-select v-model="form.businessNature" placeholder="请选择营业性质" style="width: 100%">
                  <el-option label="国有企业" value="1"></el-option>
                  <el-option label="私营企业" value="2"></el-option>
                  <el-option label="合资企业" value="3"></el-option>
                  <el-option label="外资企业" value="4"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="公司名称" prop="companyName">
                <el-input v-model="form.companyName" placeholder="请输入公司名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户类别" prop="customerType">
                <el-select v-model="form.customerType" placeholder="请选择客户类别" style="width: 100%">
                  <el-option label="直营客户" value="直营客户"></el-option>
                </el-select>
              </el-form-item>
      
            </el-col>
            <el-col :span="8">
              <el-form-item label="注册资本" prop="registeredCapital">
                <el-input v-model="form.registeredCapital" placeholder="请输入注册资本"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="客户等级" prop="customerLevel">
                <el-select v-model="form.customerLevel" placeholder="请选择客户等级" style="width: 100%">
                  <el-option label="普通用户" value="1"></el-option>
                  <el-option label="vip客户" value="4"></el-option>
                  <el-option label="svip客户" value="2"></el-option>
                  <el-option label="钻石客户" value="3"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="人员规模" prop="staffSize">
                <el-select v-model="form.staffSize" placeholder="请选择人员规模" style="width: 100%">
                  <el-option label="小微企业" value="1"></el-option>
                  <el-option label="中小企业" value="2"></el-option>
                  <el-option label="大型企业" value="3"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="所在地区" prop="region">
                  <el-select v-model="form.region" placeholder="请选择地区" style="width: 100%">
                    <el-option
                      v-for="region in regions"
                      :key="region.provinceCode"
                      :label="region.provinceName"
                      :value="region.provinceCode">
                    </el-option>
                  </el-select>
                </el-form-item>
            </el-col>
          </el-row>


          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="公司地址" prop="companyAddress">
                <el-input v-model="form.companyAddress" placeholder="请选择或输入公司地址">
                  <i slot="suffix" class="el-icon-location-outline" style="cursor: pointer"></i>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="注册地址" prop="registeredAddress">
                <el-input v-model="form.registeredAddress" placeholder="请输入注册地址"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="统一信用代码" prop="creditCode">
                <el-input v-model="form.creditCode" placeholder="请输入统一信用代码"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="状态" prop="status">
                <el-checkbox v-model="form.status" :true-value="1" :false-value="0">
                  启用
                </el-checkbox>
              </el-form-item>
            </el-col>

          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remarks">
                <el-input type="textarea" v-model="form.remarks" placeholder="请输入备注"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="section">
        <h3>联系方式</h3>
        <el-form :model="contactForm" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="法人代表" prop="legalRepresentative">
                <el-input v-model="contactForm.legalRepresentative" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="公司电话" prop="companyPhone">
                <el-input v-model="contactForm.companyPhone" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="联系人" prop="contactPerson" required>
                <el-input v-model="contactForm.contactPerson" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系电话" prop="contactPhone" required>
                <el-input v-model="contactForm.contactPhone" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="部门" prop="department">
                <el-input v-model="contactForm.department" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="职位" prop="position">
                <el-input v-model="contactForm.position" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="微信" prop="wechat">
                <el-input v-model="contactForm.wechat" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="contactForm.email" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="section">
  <h3>财务信息</h3>
  <el-form :model="financeForm" label-width="100px">
    <el-row :gutter="20">
      <el-col :span="8">
      <el-form-item label="开户银行" prop="bank" required>
        <el-select 
          v-model="financeForm.bank" 
          placeholder="请选择开户银行" 
          clearable 
          @change="handleBankChange">
          <el-option
            v-for="(bank, index) in bankList"
            :key="index"
            :label="bank.bankName" 
            :value="bank.id">      
          </el-option>
        </el-select>
      </el-form-item>

      
    </el-col>

      <el-col :span="8">
        <el-form-item label="账户名称" prop="accountName">
          <el-input v-model="financeForm.accountName" placeholder="请输入"></el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="银行账号" prop="bankAccount" required>
          <el-input v-model="financeForm.bankAccount" placeholder="请输入"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="统一认识码" prop="taxId" required>
          <el-input v-model="financeForm.taxId" disabled ></el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="网点名称" prop="branchName">
          <el-input v-model="financeForm.branchName"  disabled></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="税率" prop="taxRate">
          <el-input v-model="financeForm.taxRate"  disabled></el-input>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</div>

<template>
  <div class="section">
    <h3>交货地址</h3>
    <el-form label-width="100px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="交货地址">
            <div class="address-list">
              <div v-for="(address, index) in deliveryAddresses" :key="index" class="address-item">
                <el-select v-model="address.region" placeholder="请选择所在地区" style="width: 200px; margin-right: 10px;">
                  <el-option
                      v-for="region in regions"
                      :key="region.provinceCode"
                      :label="region.provinceName"
                      :value="region.provinceCode">
                    </el-option>
                </el-select>
                <el-input
                  v-model="address.detail"
                  placeholder="请选择或输入详细地址"
                  style="width: 300px">
                  <!-- 点击地图图标，触发地图选择功能 -->
                  <i slot="suffix"
                    class="el-icon-location-outline"
                    style="cursor: pointer;"
                    @click="openMapDialog(index)">
                  </i>
                </el-input>
                <el-button
                  type="text"
                  icon="el-icon-plus"
                  @click="addAddress"
                  v-if="index === 0">
                </el-button>
                <el-button
                  type="text"
                  icon="el-icon-minus"
                  style="color: #F56C6C"
                  @click="removeAddress(index)"
                  v-else>
                </el-button>
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 地图选择弹窗 -->
    <el-dialog :visible.sync="mapDialogVisible" title="选择地址" width="70%">
      <div id="map-container" style="width: 100%; height: 400px;"></div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="mapDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddress">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

    </div>
  </div>
</template>

<script>
export default {
  name: 'AddCustomer',
  data() {
    return {
      form: {
        customerNo: '',
        isSystemNo: true,
        customerName: '',
        businessNature: '',
        companyName: '',
        industry: '',
        registeredCapital: '',
        customerLevel: '',
        region: '',
        customerType: '',
        staffSize: '',
        companyAddress: '',
        registeredAddress: '',
        creditCode: '',
        status: true,
        remarks: ''
      },
      contactForm: {
        legalRepresentative: '',
        companyPhone: '',
        contactPerson: '',
        contactPhone: '',
        department: '',
        position: '',
        wechat: '',
        email: ''
      },
      financeForm: {
        bank: '',
        accountName: '',
        bankAccount: '',
        taxId: '',
        branchName: '',
        taxRate: ''
      },
      deliveryAddresses: [
        { region: '', detail: '' }
      ],
      rules: {
        customerName: [
          { required: true, message: '请输入客户名称', trigger: 'blur' }
        ],
        contactPerson: [
          { required: true, message: '请输入联系人', trigger: 'blur' }
        ],
        contactPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ],
        bank: [
          { required: true, message: '请输入开户银行', trigger: 'blur' }
        ],
        bankAccount: [
          { required: true, message: '请输入银行账号', trigger: 'blur' }
        ],
        taxId: [
          { required: true, message: '请输入统一认识码', trigger: 'blur' }
        ]
      },
      financeForm: {
        bank: '', // 选中的银行ID
        accountName: '', // 账户名称
        bankAccount: '', // 银行账号
        taxId: '', // 统一识别码
        branchName: '', // 网点名称
        taxRate: '' // 税率
      },
      bankList: [], // 银行信息列表
      regions: [], // 用于存储地区数据
      mapDialogVisible: false,
      selectedAddressIndex: null,
      map: null,
      marker: null,
      deliveryAddresses: [
        { region: '', detail: '' }
      ],

    
    }
  },
  methods: {
       // 获取银行信息
       fetchBankList() {
        this.$axios.post('/api/client-server/client/queryBank')  // 发送 GET 请求
        .then(resp => {
          if(resp.data.code==200){
            this.bankList = resp.data.data;  // 请求成功，处理返回的数据
          }     
        })
        .catch(error => {
          console.error('获取银行信息失败', error);  // 请求失败，处理错误
        });
    },
    // 获取地区信息
      fetchRegionList() {
        this.$axios.post('/api/client-server/client/queryRegion')  // 发送 GET 请求
        .then(resp => {
          if(resp.data.code==200){
            this.regions = resp.data.data;  // 请求成功，处理返回的数据
          }     
        })
        .catch(error => {
          console.error("获取地区数据失败:", error);  // 请求失败，处理错误
        });
    },
    // 处理银行选择变化
    handleBankChange(selectedBankId) {
      const selectedBank = this.bankList.find(bank => bank.id === selectedBankId);
      if (selectedBank) {
        this.financeForm.branchName = selectedBank.branchName;
        this.financeForm.taxRate = selectedBank.taxRate;
        this.financeForm.taxId = selectedBank.taxId;
      } else {
        this.financeForm.branchName = '';
        this.financeForm.taxRate = '';
      }
    },
    handleSystemNoChange() {
    if (this.form.isSystemNo) {
      this.form.customerNo = '';
    } else {
      // 用户取消勾选时，允许手动输入
      this.form.customerNo = ''; // 可以清空已填写的客户编号
    }
    },
    // 打开地图选择弹窗
    openMapDialog(index) {
      this.selectedAddressIndex = index;
      this.mapDialogVisible = true;

      this.$nextTick(() => {
        if (!this.map) {
          this.initMap();
        }
      });
    },

    // 初始化高德地图
    initMap() {
      this.map = new AMap.Map('map-container', {
        zoom: 10,
        center: [116.397428, 39.90923], // 默认中心点，北京
      });

      // 添加单击事件，用于设置标记点
      this.map.on('click', (e) => {
        const { lng, lat } = e.lnglat;

        // 如果已有 marker，更新位置；否则创建 marker
        if (this.marker) {
          this.marker.setPosition([lng, lat]);
        } else {
          this.marker = new AMap.Marker({
            position: [lng, lat],
            map: this.map,
          });
        }
      });
    },

    // 确认选择地址
    confirmAddress() {
      if (this.marker) {
        const position = this.marker.getPosition();

        // 使用高德逆地理编码服务获取详细地址
        const geocoder = new AMap.Geocoder();
        geocoder.getAddress(position, (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            const detail = result.regeocode.formattedAddress;

            // 更新对应地址项
            this.deliveryAddresses[this.selectedAddressIndex].detail = detail;
            this.deliveryAddresses[this.selectedAddressIndex].region = result.regeocode.addressComponent.adcode;

            this.mapDialogVisible = false;
          } else {
            this.$message.error('获取地址失败，请重试');
          }
        });
      } else {
        this.$message.warning('请在地图上选择一个位置');
      }
    },

    // 添加新的交货地址
    addAddress() {
      this.deliveryAddresses.push({ region: '', detail: '' });
    },

    // 删除交货地址
    removeAddress(index) {
      this.deliveryAddresses.splice(index, 1);
    },

    addAddress() {
      this.deliveryAddresses.push({ region: '', detail: '' });
    },
    removeAddress(index) {
      this.deliveryAddresses.splice(index, 1);
    }
  },
  created(){
    this.fetchBankList() 
    this.fetchRegionList()

  }
}
</script>

<style scoped>
.add-customer {
  padding: 20px;
  background-color: #fff;
}
.section {
  margin-bottom: 30px;
}
h2 {
  margin-bottom: 20px;
  font-size: 20px;
  font-weight: 500;
}
h3 {
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: 500;
  color: #606266;
}
.form-container {
  max-width: 1200px;
}
.el-select {
  width: 100%;
}
.address-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.address-item {
  display: flex;
  align-items: center;
  gap: 10px;
}
.el-button [class^="el-icon-"] {
  margin-right: 0;
}
</style> 